import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAdminStore } from '@/stores'
import router from '@/router'

const BASE_API = import.meta.env.VITE_BASE_API
const request = axios.create({
  baseURL: BASE_API,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = useAdminStore().token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    return config
  },

  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data
    if (response.status < 200 || response.status >= 300) {
      return Promise.reject(new Error(res.message))
    }

    return res
  },

  (error) => {
    const message = error.response?.data.message
    const status = error.response?.status

    switch (status) {
      case 400:
        ElMessage.error(message || '请求参数错误')
        break
      case 401:
        ElMessage.error(message || '未授权或token过期')
        useAdminStore().clearToken()
        router.push({ name: 'AdminLogin' })
        break
      case 403:
        ElMessage.error(message || '没有权限')
        break
      case 404:
        ElMessage.error(message || '请求资源不存在')
        break
      case 500:
        ElMessage.error(message || '服务器错误')
        break
      default:
        ElMessage.error(message || `请求失败，状态码为：${status}`)
    }

    return Promise.reject(error)
  },
)

export default request
